//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
/*++


Module Name:

    CameraDriver.cpp

Abstract:

    Template camera driver for DSHOW

Notes:
    

Revision History:

--*/

#include <windows.h>
#include <pm.h>
#include <devload.h>
#include <nkintr.h>

#define CAMINTERFACE
#include "CameraDriver.h"

//TODO : More investigation needed for AdvertiseInterface

EXTERN_C
DWORD
CAM_Init(
    VOID * pContext
    )
{    
    CAMERADEVICE * pCamDev = NULL;
    DEBUGMSG(ZONE_INIT, (_T("CAM_Init: context %s\n"), pContext));
    
    if( OEM_CERTIFY_TRUST != CeGetCallerTrust() )
    {
        SetLastError(ERROR_ACCESS_DENIED);
    }
    else
    {
        pCamDev = new CAMERADEVICE;
    
        if ( NULL != pCamDev )
        {
            // NOTE: real drivers would need to validate pContext before dereferencing the pointer
            if ( false == pCamDev->Initialize( pContext ) )
            {
                SetLastError( ERROR_INVALID_HANDLE );
                SAFEDELETE( pCamDev );
                CAMMSG( ZONE_INIT|ZONE_ERROR, ( _T("CAM_Init: Initialization Failed") ) );
            }
        }
        else
        {
            SetLastError( ERROR_OUTOFMEMORY );
        }
    }
    
    DEBUGMSG( ZONE_INIT, ( _T("CAM_Init: returning 0x%08x\r\n"), reinterpret_cast<DWORD>( pCamDev ) ) );

    return reinterpret_cast<DWORD>( pCamDev );
}


EXTERN_C
BOOL
CAM_Deinit(
    DWORD dwContext
    )
{
    DEBUGMSG( ZONE_INIT, ( _T("CAM_Deinit\r\n") ) );

    CAMERADEVICE * pCamDevice = reinterpret_cast<CAMERADEVICE *>( dwContext );
    SAFEDELETE( pCamDevice );

    return TRUE;
}


EXTERN_C
BOOL
CAM_IOControl(
    DWORD   dwContext,
    DWORD   Ioctl,
    UCHAR * pInBufUnmapped,
    DWORD   InBufLen, 
    UCHAR * pOutBufUnmapped,
    DWORD   OutBufLen,
    DWORD * pdwBytesTransferred
   )
{
    //DEBUGMSG( ZONE_IOCTL, ( _T("CAM_IOControl(%08x): IOCTL:0x%x, InBuf:0x%x, InBufLen:%d, OutBuf:0x%x, OutBufLen:0x%x)\r\n"), dwContext, Ioctl, pInBufUnmapped, InBufLen, pOutBufUnmapped, OutBufLen ) );

    UCHAR * pInBuf = NULL;
    UCHAR * pOutBuf = NULL;
    DWORD dwErr = ERROR_SUCCESS;
    BOOL  bRc   = FALSE;
    
    /*if ( ( NULL == pInBufUnmapped )
         || ( InBufLen < sizeof ( CSPROPERTY ) )
         || ( NULL == pdwBytesTransferred ) )
    {
        SetLastError( ERROR_INVALID_PARAMETER );

        return bRc;
    }*/

    pInBuf = (UCHAR*) MapCallerPtr( pInBufUnmapped, InBufLen );
    if(( pInBuf == NULL ) && ( pInBufUnmapped != NULL ))
    {
        CAMMSG( ZONE_IOCTL|ZONE_ERROR, ( _T("CAM_IOControl(%08x): CAM_IOControl. MapCallerPtr failed for incoming buffer.\r\n"), dwContext ) );

        return ERROR_INVALID_PARAMETER;
    }

    pOutBuf = (UCHAR*) MapCallerPtr( pOutBufUnmapped, OutBufLen );
    if (( NULL == pOutBuf ) && ( pOutBufUnmapped != NULL ))
    {
        CAMMSG( ZONE_IOCTL|ZONE_ERROR, ( _T("CAM_IOControl(%08x): CAM_IOControl. MapCallerPtr failed for incoming buffer.\r\n"), dwContext ) );

        return ERROR_INVALID_PARAMETER;
    }

    if ( NULL == MapCallerPtr( pdwBytesTransferred, sizeof ( DWORD ) ) )
    {
        CAMMSG( ZONE_IOCTL|ZONE_ERROR, ( _T("CAM_IOControl(%08x): CAM_IOControl. MapCallerPtr failed for dwBytesTransferred.\r\n"), dwContext ) );

        return ERROR_INVALID_PARAMETER;
    }
    
    CAMERAOPENHANDLE * pCamOpenHandle = reinterpret_cast<CAMERAOPENHANDLE *>( dwContext );
    CAMERADEVICE     * pCamDevice     = pCamOpenHandle->pCamDevice;    
    
    switch ( Ioctl )
    {
        case IOCTL_CS_PROPERTY:
        {
            DEBUGMSG( ZONE_IOCTL, ( _T("CAM_IOControl(%08x): IOCTL_CS_PROPERTY\r\n"), dwContext ) );
            CSPROPERTY       * pCsProp        = reinterpret_cast<CSPROPERTY *>( MapCallerPtr( pInBuf, sizeof ( CSPROPERTY ) ) );
    
            if ( NULL == pCsProp )
            {
                CAMMSG( ZONE_IOCTL|ZONE_ERROR, (_T("CAM_IOControl(%08x): MapCallerPtr failed for input buffer.\r\n"), dwContext ) );

                return ERROR_INVALID_PARAMETER;
            }
            __try 
            {
                if ( TRUE == IsEqualGUID( pCsProp->Set, CSPROPSETID_Pin ) )
                {
                    dwErr = pCamDevice->AdapterHandlePinRequests( pInBuf, InBufLen, pOutBuf, OutBufLen, pdwBytesTransferred );
                }
                else if ( TRUE == IsEqualGUID( pCsProp->Set, CSPROPSETID_VERSION ) )
                {
                    dwErr = pCamDevice->AdapterHandleVersion( pOutBuf, OutBufLen, pdwBytesTransferred );
                }
                else if ( TRUE == IsEqualGUID( pCsProp->Set, PROPSETID_VIDCAP_VIDEOPROCAMP ) )
                {
                    dwErr = pCamDevice->AdapterHandleVidProcAmpRequests( pInBuf,InBufLen, pOutBuf, OutBufLen, pdwBytesTransferred );
                }
                else if ( TRUE == IsEqualGUID( pCsProp->Set, PROPSETID_VIDCAP_CAMERACONTROL ) )
                {
                    dwErr = pCamDevice->AdapterHandleCamControlRequests( pInBuf,InBufLen, pOutBuf, OutBufLen, pdwBytesTransferred );
                }
                else if ( TRUE == IsEqualGUID( pCsProp->Set, PROPSETID_VIDCAP_VIDEOCOMPRESSION ) )
                {
                    dwErr = pCamDevice->AdapterHandleCompressionRequests( pInBuf,InBufLen, pOutBuf, OutBufLen, pdwBytesTransferred );
                }
                else if ( TRUE == IsEqualGUID( pCsProp->Set, PROPSETID_VIDCAP_VIDEOCONTROL ) )
                {
                    dwErr = pCamDevice->AdapterHandleVideoControlRequests( pInBuf,InBufLen, pOutBuf, OutBufLen, pdwBytesTransferred );
                }
                else if ( TRUE == IsEqualGUID( pCsProp->Set, PROPSETID_VIDCAP_DROPPEDFRAMES) )
                {   
                    dwErr = pCamDevice->AdapterHandleDroppedFramesRequests( pInBuf,InBufLen, pOutBuf, OutBufLen, pdwBytesTransferred );
                }
                else
                {
                    CAMMSG( ZONE_IOCTL|ZONE_WARN, ( _T("CAM_IOControl(%08x): Unsupported PropertySet Request%u\r\n"), dwContext, pCsProp->Set ) );
                    dwErr = ERROR_NOT_SUPPORTED;
                }
            }
            __except ( EXCEPTION_EXECUTE_HANDLER )
            {
                CAMMSG( ZONE_IOCTL, ( _T("CAM_IOControl(%08x):Exception in IOCTL_CS_PROPERTY"), dwContext ) );
            }

            break;
        }
        
        case IOCTL_POWER_CAPABILITIES:  
            RETAILMSG(1, (TEXT("CAM: IOCTL_POWER_CAPABILITIES\r\n")));
            if (pOutBufUnmapped && OutBufLen >= sizeof (POWER_CAPABILITIES) && pdwBytesTransferred) 
            {
                __try 
                {
                    PPOWER_CAPABILITIES PowerCaps = (PPOWER_CAPABILITIES)pOutBufUnmapped;

                    (void)memset(PowerCaps, 0, sizeof(*PowerCaps));
                    PowerCaps->DeviceDx = (DX_MASK((int)D0) | DX_MASK((int)D3) | DX_MASK((int)D4));
                    *pdwBytesTransferred = sizeof(*PowerCaps);
                    
                    dwErr = ERROR_SUCCESS;
                }
                __except(EXCEPTION_EXECUTE_HANDLER) 
                {
                    RETAILMSG(ZONE_ERROR, (TEXT("exception in ioctl\r\n")));
                }
            }

            break;
#if 0
        case IOCTL_POWER_QUERY: // determines whether changing power state is feasible
            RETAILMSG(1,(TEXT("CAM: Received IOCTL_POWER_QUERY\r\n")));
            if (pOutBufUnmapped && OutBufLen >= sizeof(CEDEVICE_POWER_STATE)) 
            {
                // Return a good status on any valid query, since we are always ready to
                // change power states (if asked for state we don't support, we move to next highest, eg D3->D4).
                __try 
                {
                    CEDEVICE_POWER_STATE ReqDx = *(PCEDEVICE_POWER_STATE)pOutBufUnmapped;

                    if (VALID_DX(ReqDx)) 
                    {
                        // This is a valid Dx state so return a good status.
                        dwErr = ERROR_SUCCESS;
                    }

                    RETAILMSG(ZONE_IOCTL, (TEXT("CAM: IOCTL_POWER_QUERY %s\r\n"), dwErr == ERROR_SUCCESS ? (TEXT("succeeded")) : (TEXT("failed")) ));
                }
                __except(EXCEPTION_EXECUTE_HANDLER) 
                {
                    RETAILMSG(ZONE_ERROR, (TEXT("Exception in ioctl\r\n")));
                }
            }
            break;
#endif
        case IOCTL_POWER_SET: // requests a change from one device power state to another
            RETAILMSG(1,(TEXT("CAM: Received IOCTL_POWER_SET\r\n")));
            if (pOutBufUnmapped && OutBufLen >= sizeof(CEDEVICE_POWER_STATE)) 
            {
                __try 
                {
                    CEDEVICE_POWER_STATE ReqDx = *(PCEDEVICE_POWER_STATE)pOutBufUnmapped;

                    CAMMSG(1, (TEXT("CAM%d+\n"), ReqDx));
                    if (VALID_DX(ReqDx)) 
                    {                        
                        pCamDevice->m_PDDINT->PmPower(ReqDx);
                               
                        // tell pm which state we went to:
                        *(PCEDEVICE_POWER_STATE) pOutBufUnmapped = ReqDx;
                        *pdwBytesTransferred = sizeof(CEDEVICE_POWER_STATE);

                        dwErr = ERROR_SUCCESS;
                        RETAILMSG(1, (TEXT("IOCTL_POWER_SET to D%u \r\n"), ReqDx));                                                            
                    }
                    else 
                    {
                        RETAILMSG(1, (TEXT("Invalid state request D%u\r\n"), ReqDx));
                    }
                    CAMMSG(1, (TEXT("CAM%d-\n"), ReqDx));
                }
                __except(EXCEPTION_EXECUTE_HANDLER) 
                {
                    CAMMSG(ZONE_ERROR, (TEXT("Exception in ioctl\r\n")));
                }
            }
            break;

        case IOCTL_POWER_GET: // gets the current device power state
               RETAILMSG(1,(TEXT("CAM: Received IOCTL_POWER_GET\r\n")));
                if (pOutBufUnmapped != NULL && OutBufLen >= sizeof(CEDEVICE_POWER_STATE)) 
                {
                    __try 
                    {
                        CEDEVICE_POWER_STATE   CurrentDx;   

                        CurrentDx = pCamDevice->m_PDDINT->GetSysPowerState(); 
                        *(PCEDEVICE_POWER_STATE)pOutBufUnmapped = CurrentDx;  

                        dwErr = ERROR_SUCCESS;

                        RETAILMSG(1, (TEXT("IOCTL_POWER_GET: passing back %u\r\n"), CurrentDx));  
                    }
                    __except(EXCEPTION_EXECUTE_HANDLER) 
                    {
                        CAMMSG(ZONE_ERROR, (TEXT("Exception in ioctl\r\n")));
                    }
                }

            break;
        

        default:
        {
            CAMMSG( ZONE_IOCTL, (_T("CAM_IOControl(%08x): Unsupported IOCTL code %u\r\n"), dwContext, Ioctl ) );
            dwErr = ERROR_NOT_SUPPORTED;

            break;
        }
    }
    
    // pass back appropriate response codes
    if (dwErr!=ERROR_SUCCESS)
    {
        SetLastError(dwErr) ;
    }

    return ( ( dwErr == ERROR_SUCCESS ) ? TRUE : FALSE );
}


EXTERN_C
DWORD
CAM_Open(
    DWORD Context, 
    DWORD Access,
    DWORD ShareMode
    )
{
    DEBUGMSG( ZONE_FUNCTION, ( _T("CAM_Open(%x, 0x%x, 0x%x)\r\n"), Context, Access, ShareMode ) );

    UNREFERENCED_PARAMETER( ShareMode );
    UNREFERENCED_PARAMETER( Access );

    // TODO : HANDLE ShareMode and Access parameters
    
    CAMERADEVICE     * pCamDevice     = reinterpret_cast<CAMERADEVICE *>( Context );
    CAMERAOPENHANDLE * pCamOpenHandle = NULL;
    HANDLE             hCurrentProc   = NULL;
    
    hCurrentProc = GetCallerProcess();

    ASSERT( pCamDevice != NULL );

    if ( pCamDevice->BindApplicationProc( hCurrentProc ) )
    {
        pCamOpenHandle = new CAMERAOPENHANDLE;

        if ( NULL == pCamOpenHandle )
        {
            RETAILMSG( ZONE_FUNCTION, ( _T("CAM_Open(%x): Not enought memory to create open handle\r\n"), Context ) );
        }
        else
        {
            pCamOpenHandle->pCamDevice = pCamDevice;
        }
    }
    else
    {
        SetLastError( ERROR_ALREADY_INITIALIZED );
    }

    return reinterpret_cast<DWORD>( pCamOpenHandle );
}


EXTERN_C
BOOL  
CAM_Close(
    DWORD Context
    ) 
{
    DEBUGMSG( ZONE_FUNCTION, ( _T("CAM_Close(%x)\r\n"), Context ) );
    
    PCAMERAOPENHANDLE pCamOpenHandle = reinterpret_cast<PCAMERAOPENHANDLE>( Context );

    pCamOpenHandle->pCamDevice->UnBindApplicationProc( );
    SAFEDELETE( pCamOpenHandle ) ;

    return TRUE;
}

